package com.nsoft.server.serviceImpl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.NoResultException;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.nsoft.server.master.beans.UserMaster;
import com.nsoft.server.service.dao.UserDao;
import com.nsoft.server.service.main.UserService;
import com.nsoft.thickclient.beanUtils.BeanUtilities;
import com.nsoft.thickclient.trackMove.intr.user.User;

public class UserServiceImpl implements UserService {

	public UserDao userDao;

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Transactional
	public User saveUser(User user) {
		UserMaster userdetails = null;
		if (user.getId() == null)
			userdetails = new UserMaster();
		else
			userdetails = userDao.findById(
					new Integer(user.getId().intValue()), true);
		userdetails.setUserCharUsername(user.getName());
		userdetails.setUserCharPassword(user.getPassword());
		if (user.getRole().equals(User.ADMIN))
			userdetails.setUserCharUserid(1);
		if (user.getRole().equals(User.USER))
			userdetails.setUserCharUserid(2);
		if (user.getRole().equals(User.REPORTER))
			userdetails.setUserCharUserid(3);
		userdetails.setUserDateCreated(user.getCreationDate());
		userdetails.setUserDatePwdexpiry(user.getExpiryDate());
		userdetails.setUserDatePwdsetdate(user.getPasswordResetDate());
		userdetails.setUserCharRole(user.getRole());
		UserMaster savedUser = userDao.makePersistent(userdetails);
		user.setId(new Long(savedUser.getUserCharUserid()));
		return user;
	}

	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public UserMaster getUserdetails(Long id) {
		return userDao.findById(new Integer(id.intValue()), false);
	}

	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public UserMaster getbyNamePass(User user) throws NoResultException {
		return userDao.getbyNamePass(user);
	}

	public List<User> searchUsers(User user) {

		List<UserMaster> list = userDao.searchUsers(user);
		List<User> partyList = new ArrayList<User>();
		String[] sourceNames = new String[] { "userCharUserid",
				"userCharUsername", "userCharUsername", "userCharPassword",
				"userDateCreated", "userDatePwdexpiry", "userCharRole",
				"userDatePwdsetdate", };

		String[] destinationNames = new String[] { "id", "name", "login",
				"password", "creationDate", "expiryDate", "role",
				"passwordResetDate", };

		for (UserMaster userMaster : list) {
			User user2 = new User();
			BeanUtilities.copyProerties(userMaster, user2, sourceNames,
					destinationNames);
			partyList.add(user2);
		}
		return partyList;
	}

}
